from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render,HttpResponse
from bson import ObjectId
# Create your views here.
from django.utils import timezone
from django.utils.translation import get_language
from django.views.decorators.csrf import ensure_csrf_cookie
import json
import os
import logging

from django.views.decorators.http import require_POST,require_GET,require_http_methods
from django.utils.translation import gettext as _
from mrc.jwt_token import mrc_is_authenticated, get_username, get_user_info
from mrc.models import mrc_backgrounds, mrc_humans
from mrc_platform.settings import BASE_DIR, MEDIA_ROOT, MEDIA_URL, DATA_API_PROTOCOL, DATA_API_DOMAIN, MRC_TOKEN
from tools_pack.oled_drow import oled_show_text
from tools_pack.zip_parses import zip_operate
import requests
import datetime


log = logging.getLogger('proscenium')
code_effective_time=5*60 #验证码有效时间5分钟


@ensure_csrf_cookie
def index(request):
    authenticated=mrc_is_authenticated(request)


    token = request.COOKIES.get(MRC_TOKEN, '')
    username = get_username(token)

    items={
        'mrc_is_authenticated':authenticated,
        'mrc_username':username
    }

    return render(request,'index.html',items)



@ensure_csrf_cookie
@require_http_methods(['GET','POST'])
def login(request):
    log.info("用户请求数据 %s" %request.POST)
    items={}
    items["message"]=""
    if request.method=='GET':
        return render(request,'sign-in.html',items)
    else:
        phone=request.POST.get('phone','')
        sms_code=request.POST.get('code','')
        remember=request.POST.get('remember','')
        if phone=='' or sms_code=='':
            items["message"] = _("手机号码或者短信验证码不能为空")
            return render(request, 'sign-in.html', items)

        remember_second=1*24*60*60
        if remember=='1':
            remember_second=7*24*60*60

        data_dict={"phone":phone,"sms_code":sms_code,"remember":remember_second,"language":get_language()}
        url=DATA_API_PROTOCOL+DATA_API_DOMAIN+'/api/v1/login/'
        headers = {'Content-Type': 'application/json'}
        log.info('send data %s' %data_dict)
        try:
            response=requests.post(url,json=data_dict,headers=headers)
        except Exception as e:
            log.warning(e)
            items["message"] = _("登录失败，网络错误，请稍等再试！")
            return render(request, 'sign-in.html', items)
        if response.status_code!=200:
            log.warning('调用登录api错误 http返回码 %s' %response.status_code)
            items["message"] = _("登录失败，网络错误，请稍等再试！")
            return render(request, 'sign-in.html', items)
        json_data=response.json()
        log.info("return data %s" % json_data)
        code=json_data.get('code',1)
        if code!=0:
            log.warning('调用登录api错误 返回错误信息 %s' % json_data.get('message',''))
            items["message"] = json_data.get('message','')
            return render(request, 'sign-in.html', items)
        token=json_data.get('token','')

        if token=='':
            log.warning('调用登录api错误 token为空  token: %s' %(token))
            items["message"] = json_data.get('message', '')
            return render(request, 'sign-in.html', items)

        http_response=HttpResponseRedirect(reverse('mrc:index'))
        http_response.set_cookie(MRC_TOKEN,token,remember_second)
        return http_response

def logout(request):
    http_response=HttpResponseRedirect(reverse('mrc:index'))
    http_response.delete_cookie(MRC_TOKEN,)
    return http_response

@require_POST
def get_sms_code(request):
    """
    2018-05-21 add by jack
    获取短信验证码
    :param request:
    :return:
    """
    log.info("用户请求数据 %s" % request.POST)
    items={
        "is_success":False,
        "message":""
    }
    phone=request.POST.get("phone","")
    data_dict = {"phone": phone,"language":get_language()}
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_sms_code/'
    headers = {'Content-Type': 'application/json'}
    log.info('send data %s' % data_dict)
    try:
        response=requests.post(url,json=data_dict,headers=headers)
    except Exception as e:
        log.warning(e)
        items['message']=_("获取短信验证码错误!")
        data=json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type="application/json")
    if response.status_code != 200:
        log.warning('调用sms code api错误 http返回码 %s' % response.status_code)
        items["message"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type="application/json")

    json_data = response.json()
    log.info("return data %s" % json_data)
    code = json_data.get('code', 1)
    if code != 0:
        log.warning('调用sms code api错误 返回错误信息 %s' % json_data.get('message', ''))
        items['message'] = json_data.get('message', '')
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type="application/json")
    else:
        items["is_success"]=True
        data=json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type="application/json")







@require_POST
def upload_online_run_xml(request):
    '''
    2018-04-25 add by jack
    记录用户烧录或运行的工程文件
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    data = request.body.decode("utf-8")
    json_data = json.loads(data)
    xml=json_data.get('xml','')
    block_count=json_data.get('block_count',0)  #在工作空间的积木数量
    user_edit=json_data.get('user_edit',0)  #是否用户编辑的 1是 0否
    arduino_code=json_data.get('arduino_code','')
    mode=json_data.get('mode','')  #0离线模式 1在线模式
    if isinstance(arduino_code,str)==False:
        arduino_code=''

    token = request.COOKIES.get(MRC_TOKEN, '')
    if token=='':
        log.warning("用户未登录")
        return HttpResponse()
    if isinstance(block_count,int)==True and block_count>0 and user_edit==1 and isinstance(xml,str)==True and xml!='' and mode in [0,1]:
        data_dict = {"xml": xml,"arduino":arduino_code,"mode":mode,"language":get_language()}
        log.info('send data %s' % data_dict)
        headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/upload_online_run_xml/'
        try:
            response = requests.post(url, json=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            return HttpResponse()
        if response.status_code != 200:
            log.warning('调用upload xml api错误 http返回码 %s' % response.status_code)
            return HttpResponse()

        json_data = response.json()
        log.info("return data %s" % json_data)
        code = json_data.get('code', 1)
        if code != 0:
            log.warning('调用upload xml api错误 返回错误信息 %s' % json_data.get('message', ''))
            return HttpResponse()
        else:
            log.info("上传记录成功")
            return HttpResponse()
    else:
        log.warning("判断条件失败，不上传")
        return HttpResponse()

@require_GET
def get_history_list(request):
    """
    2018-05-04 add by jack
    获取用户的上传或运行的历史
    :param request:
    :return:
    """
    token = request.COOKIES.get(MRC_TOKEN, '')
    data_list = []
    count=10 #获取条数
    if token!="":
        headers = {'Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_history_list/'
        data_dict={"count":count,"language":get_language()}
        log.info('send data %s' % data_dict)
        try:
            response = requests.get(url,params=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            data=json.dumps(data_list)
            log.info('返回结果 %s' % data_list)
            return HttpResponse(data, content_type='application/json')
        if response.status_code != 200:
            log.warning('调用history list api错误 http返回码 %s' % response.status_code)
            data = json.dumps(data_list)
            log.info('返回结果 %s' % data_list)
            return HttpResponse(data, content_type='application/json')
        json_data = response.json()
        log.info("return data %s" % json_data)
        code = json_data.get('code', 1)
        if code != 0:
            log.warning('调用history list api错误 返回错误信息 %s' % json_data.get('message', ''))
            data = json.dumps(data_list)
            log.info('返回结果 %s' % data_list)
            return HttpResponse(data, content_type='application/json')
        data_dict=json_data.get('data',{})
        if isinstance(data_dict, dict) == True and data_dict.keys().__len__() > 0:
            data_list=data_dict.items()
            data_list=sorted(data_list,key=lambda x:x[0])
            data = json.dumps(data_list)
            log.info('返回结果 %s' % data_list)
            return HttpResponse(data, content_type='application/json')
        else:
            data = json.dumps(data_list)
            log.info('返回结果 %s' % data_list)
            return HttpResponse(data, content_type='application/json')
    else:
        log.warning("用户未登录")
        data = json.dumps(data_list)
        log.info('返回结果 %s' % data_list)
        return HttpResponse(data, content_type='application/json')

@require_GET
def get_xml_history(request):
    """
    2018-05-05 add by jack
    获取用户某个历史记录
    :param request:
    :return:
    """

    log.info('用户申请数据 %s' % request.GET)
    items={
        "code":1,
        "xml_data":"",
        "msg":"",
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token=="":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        id=request.GET.get("xml_id","")   #记录的id
        if id=="":
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        headers = {'Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_xml_history/'
        data_dict={"xml_id": id,"language":get_language()}
        log.info('send data %s' % data_dict)
        try:
            response = requests.get(url, params=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        if response.status_code != 200:
            log.warning('调用history xml api错误 http返回码 %s' % response.status_code)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        json_data = response.json()
        log.info("return data %s" % json_data)
        code = json_data.get('code', 1)
        if code != 0:
            log.warning('调用history xml api错误 返回错误信息 %s' % json_data.get('message', ''))
            items["msg"]=json_data.get('message', '')
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        else:
            items["code"]=0
            items["xml_data"]=json_data.get('data','')
            items["msg"]=_("获取历史成功")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')

@require_GET
def delete_xml_history(request):
    """
    2018-05-07 add by jack
    用户删除自己的积木上传或运行历史
    :param request:
    :return:
    """
    log.info('用户申请数据 %s' % request.GET)
    items = {
        "code": 1,
        "msg": "",
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        id = request.GET.get("xml_id", "")  # 记录的id
        if id == "":
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/delete_xml_history/'
        data_dict={"xml_id": id,"language":get_language()}
        log.info('send data %s' % data_dict)
        try:
            response = requests.post(url, json=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        if response.status_code != 200:
            log.warning('调用history delete api错误 http返回码 %s' % response.status_code)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        json_data = response.json()
        log.info("return data %s" %json_data)
        code = json_data.get('code', 1)
        if code != 0:
            log.warning('调用history delete api错误 返回错误信息 %s' % json_data.get('message', ''))
            items['msg']=json_data.get('message', '')
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        else:
            items["code"] = 0
            items["msg"] = _("删除历史成功")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')

@require_GET
def get_example_list(request):
    '''
    2018-05-30 add by jack
    获取例子工程列表
    :param request:
    :return:
    '''
    examples=[]
    lang=get_language()  #获取当前使用的语言代码
    example_dir=os.path.join(BASE_DIR,'example',lang)
    if os.path.isdir(example_dir) == True:
        for (root, dirs, files) in os.walk(example_dir):
            for sub_file in files:
                examples.append(sub_file.split('.')[0])
    data=json.dumps(examples)
    return HttpResponse(data,content_type='application/json')


@require_GET
def get_example_project(request):
    '''
    2018-05-30 add by jack
    获取指定例子工程的内容
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.GET)
    items={}
    name=request.GET.get('name','')
    if name=='':
        data=json.dumps(items)
        return HttpResponse(data,content_type='application/json')
    lang = get_language()  # 获取当前使用的语言代码
    name+='.mt'
    example_file = os.path.join(BASE_DIR, 'example', lang,name)
    if os.path.isfile(example_file)==False:
        data = json.dumps(items)
        return HttpResponse(data, content_type='application/json')
    zip_obj = zip_operate(example_file)
    try:
        items = zip_obj.file_list_info()
    except Ellipsis as e:
        log.warning(e)
    data = json.dumps(items)
    return HttpResponse(data, content_type='application/json')

@require_GET
def get_cloud_project_list(request):
    '''
    2018-06-12 add by jack
    获取用户存储在云端的工程记录
    :param request:
    :return:
    '''
    items = {
        "code": 1,
        "msg": "",
        "data":[]
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:

        user_info=get_user_info(token)

        headers = {'Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/block/user/%s/' %user_info["id"]
        data_dict = {"language": get_language()}
        log.info('send data %s' % data_dict)
        try:
            response = requests.get(url, params=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        if response.status_code != 200:
            log.warning('调用cloud project list api错误 http返回码 %s' % response.status_code)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        json_data = response.json()
        log.info("return data %s" % json_data)

        if isinstance(json_data,list)==False:
            items['code']=0
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        else:
            data_list=[]
            for sub in json_data:
                one_item={}
                one_item['id']=sub.get('id','')
                one_item['title']=sub.get('title','')
                one_item['author']=sub.get('author','')
                one_item['update']=sub.get('update','')
                data_list.append(one_item)
            items['code'] = 0
            items["data"]=data_list
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')



@require_POST
def change_cloud_project_name(request):
    '''
    2018-06-12 add by jack
    修改某个云端工程的工程名字
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    items = {
        "code": 1,
        "msg": "",
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        try:
            request_data=json.loads(request.body.decode('utf-8'))
        except Exception as e:
            log.warning(e)
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')

        id=request_data.get('id','')
        user_id=request_data.get('user_id','')
        name=request_data.get('name','')
        try:
            user_id=int(user_id)
        except Exception as e:
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        headers = {'Content-Type': 'application/json','Authorization': 'JWT %s' % token}
        url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/block/%s/' %id
        data_dict = {"language": get_language(),"author":user_id,"title":name}
        log.info('send data %s' % data_dict)
        try:
            response = requests.put(url, json=data_dict, headers=headers)
        except Exception as e:
            log.warning(e)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        if response.status_code != 200:
            log.warning('调用change_cloud_project_name api错误 http返回码 %s' % response.status_code)
            items["msg"] = _("网络错误，请稍等再试！")
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
        json_data = response.json()
        log.info("return data %s" % json_data)

        items['code'] = 0
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')


@require_POST
def get_cloud_project_data(request):
    '''
    2018-06-13 add by jack
    获取某个云端工程数据
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    items = {
        "code": 1,
        "msg": "",
        "data":{}
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        try:
            request_data = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            log.warning(e)
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
    id=request_data.get('id','')

    headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/block/%s/' % id
    data_dict = {"language": get_language()}
    log.info('send data %s' % data_dict)
    try:
        response = requests.get(url, params=data_dict, headers=headers)
    except Exception as e:
        log.warning(e)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    if response.status_code != 200:
        log.warning('调用get_cloud_project_data api错误 http返回码 %s' % response.status_code)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    json_data = response.json()
    log.info("return data %s" % json_data)

    items['code'] = 0
    items["data"]=json_data
    data = json.dumps(items)
    log.info('返回结果 %s' % items)
    return HttpResponse(data, content_type='application/json')

@require_POST
def save_cloud_project_data(request):
    """
    2018-06-13 add by jack
    保存工程到云储存
    :param request:
    :return:
    """
    log.info('用户申请数据 %s' % request.body)
    items = {
        "code": 1,
        "msg": "",
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        try:
            request_data = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            log.warning(e)
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
    headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/get_user_info/'
    try:
        response = requests.get(url, headers=headers)
    except Exception as e:
        log.warning(e)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    if response.status_code != 200:
        log.warning('调用save_cloud_project_data api错误 http返回码 %s' % response.status_code)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    user_json=response.json()
    log.info("user info: %s" %user_json)

    user_id =user_json.get('id','')
    xml_data=request_data.get('xml','')
    title=request_data.get('title','')


    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/block/'
    data_dict = {"language": get_language(),'title':title,'author':user_id,'xml_content':xml_data}
    log.info('send data %s' % data_dict)
    try:
        response = requests.post(url, json=data_dict, headers=headers)
    except Exception as e:
        log.warning(e)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    if response.status_code != 201:
        log.warning('调用save_cloud_project_data api错误 http返回码 %s' % response.status_code)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    json_data = response.json()
    log.info("return data %s" % json_data)

    items['code'] = 0
    items["msg"]=_("保存工程到云端成功！")
    data = json.dumps(items)
    log.info('返回结果 %s' % items)
    return HttpResponse(data, content_type='application/json')


@require_POST
def delete_cloud_project_data(request):
    '''
    2018-06-13 add by jack
    删除云端的某个工程
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    items = {
        "code": 1,
        "msg": "",
    }
    token = request.COOKIES.get(MRC_TOKEN, '')
    if token == "":
        log.warning("用户未登录")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        try:
            request_data = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            log.warning(e)
            data = json.dumps(items)
            log.info('返回结果 %s' % items)
            return HttpResponse(data, content_type='application/json')
    id = request_data.get('id', '')

    headers = {'Content-Type': 'application/json', 'Authorization': 'JWT %s' % token}
    url = DATA_API_PROTOCOL + DATA_API_DOMAIN + '/api/v1/block/%s/' % id
    data_dict = {"language": get_language()}
    log.info('send data %s' % data_dict)
    try:
        response = requests.delete(url, headers=headers)
    except Exception as e:
        log.warning(e)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    if response.status_code != 204:
        log.warning('调用get_cloud_project_data api错误 http返回码 %s' % response.status_code)
        items["msg"] = _("网络错误，请稍等再试！")
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    log.info("return data %s" % {})

    items['code'] = 0
    data = json.dumps(items)
    log.info('返回结果 %s' % items)
    return HttpResponse(data, content_type='application/json')

@require_POST
def oled_display(request):
    '''
    2018-07-02 add by jack
    oled显示屏单行的中文显示格式处理
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    items = {'data': []}
    try:
        json_text=json.loads(request.body.decode('utf-8'))
    except Exception as e:
        log.warning(e)
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    keys = list(json_text.keys())
    if 'text' in keys and 'x' in keys and 'y' in keys:
        text = json_text.get('text', '')
        text = text.strip('"')
        old_obj = oled_show_text()
        hex_list = old_obj.one_row_show(text, json_text.get('x', ''), json_text.get('y', ''))
        items['data'] = hex_list
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')

@require_POST
def oled_multiple_display(request):
    '''
    2018-07-02 add by jack
    oled显示屏多行的中文显示格式处理
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.body)
    items = {'data': []}
    try:
        json_text = json.loads(request.body.decode('utf-8'))
    except Exception as e:
        log.warning(e)
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    keys = list(json_text.keys())
    if 'text_list' in keys:
        text = json_text.get('text_list', [])
        text_list = []
        for key in text:
            text_list.append(key.strip('"'))
        old_obj = oled_show_text()
        hex_list = old_obj.multiple_row_show(text_list)
        items['data'] = hex_list
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    else:
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')


def save_image_file(user_id=None,md5_str=None,file_type=None,upload_type=None,file_bytes=None):
    '''
    2018-03-21 add by jack
    根据用户保存ip人物图片或者背景图片
    :param user_id: 用户id type int
    :param md5_str: md5字符串 type string
    :param file_type: 文件后缀名 type string
    :param upload_type: 图片的上传类型 人物图还是背景图 type string
    :param file_bytes: 文件数据  type bytes
    :return: 图片url
    '''
    user_id = str(user_id)
    file_name = md5_str + '.' + file_type

    if upload_type=='background':
        user_backgrounds_path=os.path.join(BASE_DIR,MEDIA_ROOT,'user_backgrounds')
        if os.path.isdir(user_backgrounds_path)==False:
            os.mkdir(user_backgrounds_path)
        if os.path.isdir(os.path.join(user_backgrounds_path,user_id))==False:
            os.mkdir(os.path.join(user_backgrounds_path,user_id))
        file_path=os.path.join(user_backgrounds_path,user_id,file_name)
        with open(file_path,'wb') as f:
            f.write(file_bytes)
        image_url=os.path.join(MEDIA_URL,'user_backgrounds',user_id,file_name)
        mrc_backgrounds.objects.create(user_id=int(user_id), background_path=image_url)
        return image_url
    else:
        user_humans_path = os.path.join(BASE_DIR, MEDIA_ROOT, 'user_humans')
        if os.path.isdir(user_humans_path) == False:
            os.mkdir(user_humans_path)
        if os.path.isdir(os.path.join(user_humans_path, user_id)) == False:
            os.mkdir(os.path.join(user_humans_path, user_id))
        file_path = os.path.join(user_humans_path, user_id, file_name)
        with open(file_path, 'wb') as f:
            f.write(file_bytes)
        image_url = os.path.join(MEDIA_URL, 'user_humans', user_id, file_name)
        mrc_humans.objects.create(user_id=int(user_id), human_path=image_url)
        return image_url


@require_POST
def upload_file(request):
    '''
    2018-03-21 add by jack
    用户上传ip人物图片或背景图片
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.POST)
    log.info('用户文件数据 %s' % request.FILES)

    items={
        'upload_type':'',
        'status':0,
        'url':''
    }

    upload_type_list=['human','background']  #上传图片类型
    file_md5=request.POST.get('file_md5','') #md5字符串
    upload_type=request.POST.get('upload_type','')  #图片类型
    file_name=request.POST.get('file_name','')  #上传图片的名字
    file_data=request.FILES.get('uploadcore-input',None)  #文件对象

    token = request.COOKIES.get(MRC_TOKEN, '')

    if token == "":
        log.warning("用户未登录")
        items['upload_type'] = upload_type
        items['url'] = ""
        items['status'] = 0
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json', status=401)
    user_info = get_user_info(token)
    try:
        user_id=int(user_info["id"])
    except Exception as e:
        log.warning(e)
        log.warning("获取用户id错误")
        items['upload_type'] = upload_type
        items['url'] = ""
        items['status'] = 0
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json', status=401)

    if upload_type=='' or file_md5=='' or file_name=='' or upload_type not in upload_type_list:
        log.error('request.data 数据错误')
        data=json.dumps(items)
        log.info('返回结果 %s' %items)
        return HttpResponse(data,content_type='application/json')
    if file_data==None:
        log.error('文件对象为None')
        data = json.dumps(items)
        log.info('返回结果 %s' % items)
        return HttpResponse(data, content_type='application/json')
    file_tmp=file_name.split('.')
    if file_tmp.__len__()<2:
        file_suffix='png'
    else:
        file_suffix=file_tmp[-1]


    image_url=save_image_file(user_id=user_id,md5_str=file_md5,file_type=file_suffix,upload_type=upload_type,file_bytes=file_data.read())
    items['upload_type']=upload_type
    items['url']=image_url
    items['status']=1
    data=json.dumps(items)
    log.info('返回结果 %s' % items)
    return HttpResponse(data,content_type='application/json')


@require_GET
def get_images(request):
    '''
    2018-03-22 add by jack
    获取用户上传的ip人物图片列表或者背景图片列表
    :param request:
    :return:
    '''
    log.info('用户申请数据 %s' % request.GET)
    qtype=request.GET.get('type','')   #图片类型 background  human
    if qtype not in ['background','human']:
        log.error('获取图片类型错误')
        return HttpResponse('<ul></ul>')

    token = request.COOKIES.get(MRC_TOKEN, '')
    if token!='':
        user_info = get_user_info(token)
        try:
            user_id = int(user_info["id"])
        except Exception as e:
            log.warning(e)
            user_id=None
    else:
        user_id=None


    result_text=''
    if qtype=='human':
        file_list=[]
        for root,dirs,files in os.walk(os.path.join(BASE_DIR,MEDIA_ROOT,"default_human")):
            file_list=files
        if user_id!=None:
            for human in mrc_humans.objects.filter(is_delete=0):
                if human.human_path!="" and human.human_path!=None:
                    file_list.append(human.human_path)
        for sub_human in file_list:
            image_path=os.path.join(MEDIA_URL,'default_human',sub_human)
            one_huma="<li><a href='{}'>{}</a></li>".format(image_path,image_path)
            result_text+=one_huma
    else:
        file_list = []
        for root, dirs, files in os.walk(os.path.join(BASE_DIR, MEDIA_ROOT, "default_background")):
            file_list = files

        if user_id!=None:
            for backgrounds in mrc_backgrounds.objects.filter(is_delete=0):
                if backgrounds.background_path!="" and backgrounds.background_path!=None:
                    file_list.append(backgrounds.background_path)
        for sub_background in file_list:
            image_path = os.path.join(MEDIA_URL,'default_background' ,sub_background)
            one_background="<li><a href='{}'>{}</a></li>".format(image_path,image_path)
            result_text+=one_background
    result_text='<ul>'+result_text+'</ul>'
    log.info('返回结果 %s' %result_text)
    return HttpResponse(result_text)



def get_notice_info(request):
    """
    2018-09-12 add by jack
    增加前台页面消息通知
    :param request:
    :return:
    """
    if datetime.datetime.now().year<2019 or (datetime.datetime.now().year==2019 and datetime.datetime.now().month<3):
        #在2019年3月之前显示通知
        items={
            'is_show':1,
            'message':_("MRC已经升级新版本，请从官网重新下载对应新版的MRC编程助手，此次升级主要是加强Firmata模式的功能，加强积木与积木之前上下文的关联！")
        }
    else:
        items={
            "is_show":0,
            "message":""
        }
    return HttpResponse(json.dumps(items), content_type='application/json')
